package com.example.snuposter;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	private boolean Menu_Displayed = false;
	Context context = this;
	
	@SuppressLint("HandlerLeak")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//get width, height of display
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		final int width = displaymetrics.widthPixels;
		final int height = displaymetrics.heightPixels;
		
		//create side menu:
        LinearLayout li_menu = new LinearLayout(this) {
        	@Override
        	public boolean onTouchEvent(MotionEvent ev) {
        		if (Menu_Displayed) {
        			return true;
        		} else {
        			return false;
        		}
        	}
        };
        li_menu.setLayoutParams(new LayoutParams(width, height));  
        li_menu.setOrientation(1);		//1 is vertical
        
        //side menu's listview
        ListView menu_list = new ListView(this);
        menu_list.setId(R.id.menu_list);
        menu_list.setLayoutParams(new LayoutParams(width, height));
        menu_list.setBackgroundColor(Color.GREEN);
        
        li_menu.addView(menu_list);
        
        //body: horizontal scroll view
        final HorizontalScrollView hsv = new HorizontalScrollView(this) {
        	@Override
            //do not let hsv consume the click itself. Then the view under the hsv will also consume the click so that the menu will be clicked
            public boolean onTouchEvent(MotionEvent ev) {
            	if (Menu_Displayed) {
            		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            			Log.d("Action_Down", "action");
            			if (ev.getX() > width-100) {
            				Log.d("scroll", "scroll");
            				return super.onTouchEvent(ev);
            			} else return false;
            		} else return super.onTouchEvent(ev);
                } else {
                	if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                		Log.d("debug", "debug");
                		if (ev.getX() < 100) {
                			return super.onTouchEvent(ev);
                		} else return false;
                	}
                    return super.onTouchEvent(ev);
                }
            }
            
            @Override
        	public boolean onInterceptTouchEvent(MotionEvent ev) {
        		if (Menu_Displayed) {
        			if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            			Log.d("Action_Down1", "action1");
            			if (ev.getX() > width-100) {
            				Log.d("scroll1", "scroll1");
            				return super.onInterceptTouchEvent(ev);
            			} else return true;
            		} else return super.onInterceptTouchEvent(ev);
        		} else {
        			return super.onInterceptTouchEvent(ev);
        		}
        	}
        };
        hsv.setLayoutParams(new LayoutParams(width, height));  
        hsv.setBackgroundColor(Color.TRANSPARENT);
        hsv.setHorizontalFadingEdgeEnabled(false);
        hsv.setVerticalFadingEdgeEnabled(false);
        
        //scroll by drag
        hsv.setOnTouchListener(new OnTouchListener () {
        	float lastPositionX = 0;
        	@Override
			public boolean onTouch(View v, MotionEvent ev) {
        		if (ev.getAction() == MotionEvent.ACTION_MOVE) {
        			lastPositionX = hsv.getScrollX();
        		} else if (ev.getAction() == MotionEvent.ACTION_UP) {
					Log.d("action_up", hsv.getScrollX()+"");
					Log.d("last position", lastPositionX+"");
					if (lastPositionX - hsv.getScrollX() > 20) {
						hsv.post(new Runnable () {
							@Override
							public void run() {
								hsv.smoothScrollTo(0, 0);
							}
						});
						Menu_Displayed = true;
					} else if (lastPositionX - hsv.getScrollX() < -20) {
						hsv.post(new Runnable () {
							@Override
							public void run() {
								hsv.smoothScrollTo(width-100, 0);
							}
						});
						Menu_Displayed = false;
					} else {
						if ((2*hsv.getScrollX()-lastPositionX) < (width-100)/2) {
							hsv.post(new Runnable () {
								@Override
								public void run() {
									hsv.smoothScrollTo(0, 0);
								}
							});
							Menu_Displayed = true;
						} else {
							hsv.post(new Runnable () {
								@Override
								public void run() {
									hsv.smoothScrollTo(width-100, 0);
								}
							});
							Menu_Displayed = false;
						}
					}
				}
				return false;
			}
        	
        });
        
        final LinearLayout li_body = new LinearLayout(this);
        li_body.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, height));  
        li_body.setOrientation(0);		//0 is horizontal
        li_body.setBackgroundColor(Color.TRANSPARENT);
        
        hsv.addView(li_body);
        
        //body: place holder(transparent)
        TextView placeholder = new TextView(this);
        placeholder.setTextColor(Color.TRANSPARENT);
        placeholder.setLayoutParams(new LayoutParams(width-100, height));  
        placeholder.setVisibility(View.INVISIBLE);
        li_body.addView(placeholder);
        
        //body: real content
        LinearLayout li_content = new LinearLayout(this);
        li_content.setLayoutParams(new LayoutParams(width, height));  
        li_content.setOrientation(1);
        
        //use this button to scroll
        Button btn_showMenu = new Button(this);
        btn_showMenu.setText("Menu");
        btn_showMenu.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        btn_showMenu.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                hsv.post(new Runnable() {
                
                    @Override
                    public void run() {
                        if(Menu_Displayed){
                            hsv.smoothScrollTo(width-100, 0);
                        }
                        else{
                            hsv.smoothScrollTo(0, 0);
                        }
                        Menu_Displayed = !Menu_Displayed;
                    }
                });
            }
        });
        
        final ListView poster_list = new ListView(this);
        poster_list.setId(R.id.poster_list);
        poster_list.setLayoutParams(new LayoutParams(width, height-300));	//300 for debug
        poster_list.setBackgroundColor(Color.CYAN);
        poster_list.setCacheColorHint(Color.TRANSPARENT);
        //test
        
        li_content.addView(btn_showMenu);
        li_content.addView(poster_list);
        
        li_body.addView(li_content);
        
        //add menu and body in to frame
        FrameLayout mainFrame = new FrameLayout(this) {
        	
        };
        mainFrame.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        mainFrame.addView(li_menu);
        mainFrame.addView(hsv);
        
        //scroll to the body real content to block the menu
        hsv.post(new Runnable() {
        
            @Override
            public void run() {
                hsv.scrollBy(width-100, 0);
            }
        });
        
        setContentView(mainFrame);
        
		//making data: thread
        final String url = "http://54.248.225.60/image/_2013-02-07T08:34:20.049923_kjhichyaaa&crop.jpg";
        final Row[] data_list = new Row[5];
        Thread[] make_row_array = new Thread[5];
        boolean[] isAlive = new boolean[5];
        
        for (int i = 0; i < 5; i++) {
        	final int location = i;
        	Thread make_row = new Thread(new Runnable() {
        		public void run() {
        			
        			Log.d("thread open", location+"");
         			makeRow(url, location+"left", url, location+"right", data_list, location);
        			Log.d("thread close", "close");
        		}
        	});
        	make_row.start();
        	isAlive[i] = make_row.isAlive();
        	make_row_array[i] = make_row;
        } 
        
        
        while (isAlive[0] || isAlive[1] || isAlive[2] || isAlive[3] || isAlive[4]) {
        	Log.d("main thread", "hold"); 	
        	
        	for (int i = 0; i < 5; i++) {
        		isAlive[i] = make_row_array[i].isAlive();
        	}
	    } 
	    
        Log.d("main thread", "restart");
        PosterAdapter adapter = new PosterAdapter(context, R.layout.listview_row, data_list);//listview_row.xml
		poster_list.setAdapter(adapter);
    
	}
	
	private void makeRow(String url_left, String title_left, String url_right, String title_right, Row[] data_list, int location) {
		Bitmap poster_left = null;
		Bitmap poster_right = null;
		Log.d("makeRow start","start");
		try{
			URL aURL = new URL(url_left);
			URLConnection conn = aURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			poster_left = BitmapFactory.decodeStream(bis);
			bis.close();
			is.close();
			Log.d("left", poster_left.toString()+"");
		}catch (IOException e) {
			Log.e("error", "Error getting left bitmap", e);
		}
		
		try {
			URL aURL = new URL(url_right);
			URLConnection conn = aURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			poster_right = BitmapFactory.decodeStream(bis);
			bis.close();
			is.close();
			Log.d("right", poster_right.toString()+"");
		} catch (IOException e) {
			Log.e("error", "Error getting right bitmap", e);
		}
		
		data_list[location] = new Row(url_left, poster_left, title_left, url_right, poster_right, title_right);
		Log.d("makeRow end", "end");
	}
}